package cn.com.tom.dao.impl;

import cn.com.tom.bean.User;
import cn.com.tom.dao.UserDao;
import cn.com.tom.util.Dbs;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

    @Override
    public boolean save(User bean) {
        Integer id = bean.id;
        String sql = "";
        List<Object> args = new ArrayList<>();

        args.add(bean.getName());
        args.add(bean.getPassword());
        args.add(bean.getEmail());

        args.add(bean.getBirthday());
        args.add(bean.getPhoto());
        args.add(bean.getIntro());

        args.add(bean.getAddress());
        args.add(bean.getPhone());

        args.add(bean.getJob());
        args.add(bean.getTrait());
        args.add(bean.getInterests());

        if (id == null || id < 1) {
            sql = "INSERT INTO user(name,password,email,birthday,photo,intro,address,phone,job,trait,interests) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
        } else {
            sql = "UPDATE user SET name=?,password=?,email=?,birthday=?,photo=?,intro=?,address=?,phone=?,job=?,trait=?,interests=? WHERE id=?";
            args.add(id);
        }

        System.out.println("sql:" + sql);
        return Dbs.save(sql, args.toArray());
    }

    @Override
    public User get(Integer id) {
        String sql = "SELECT id,created_time,name,password,email,birthday,photo,intro,address,phone,job,trait,interests FROM user WHERE id=?";
        return Dbs.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public List<User> list() {
        String sql = "SELECT id,created_time,name,password,email,birthday,photo,intro,address,phone,job,trait,interests FROM user";
        return Dbs.list(sql, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public User getUser(User user) {
        String sql = "SELECT id,password,email,photo,intro,birthday,name,address,phone,job,trait,interests FROM user WHERE email=? and password=?";
        List<User> list = Dbs.query(sql, new BeanPropertyRowMapper<>(User.class), user.email, user.password);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
